import axios from 'axios';
import Qs from 'qs'
import config from './api';
//import Cookies from 'js-cookie';
// import router from '../router';
var Cookies = require('js-cookie');

let util = {};
util.title = function(title) {
  title = title ? title + ' - 广告后台' : '广告后台';
  window.document.title = title;
};

const ajaxUrl = config.host;
util.ajax = axios.create({
  baseURL: ajaxUrl,
  transformRequest: (data) => {
    return Qs.stringify(data);
  },
  headers: {
    'Content-Type':'application/x-www-form-urlencoded; charset=utf-8',
  },
  timeout: 600000
});
// 添加请求拦截器请求头中设置token
util.ajax.interceptors.request.use(
  config => {
    var sessionId = Cookies.get('PHPSESSID');
    if(sessionId){
      config.headers.token = sessionId;
    };
    var userInfo = localStorage.getItem("userInfo");
    if(userInfo){
      userInfo = JSON.parse(userInfo);
      //cookie过期处理
      var cookiesTokens = Cookies.get('PHPSESSID');
      if(typeof cookiesTokens === 'undefined' && userInfo instanceof Object){
        cookiesTokens = userInfo.token;
      };
      var nowTime = Number((new Date()).getTime())/1000;
      if(!cookiesTokens || userInfo.tokenEnd < nowTime){
        vue.$message({
          message: '登录超时，请重新登录！',
          type: 'error',
          center: true
        });
        setTimeout(function(){
          console.log('登录超时');
        },2000);
        localStorage.removeItem("userInfo");
        Cookies.remove('PHPSESSID');
        //刷新页面，通过路由检测处理跳转至登录页
        setTimeout(function(){
          location.reload();
        },1500);
      }else{
        config.headers.token = cookiesTokens;
      }
    };
    return config;
  },
  err => {
    setTimeout(function(){
      console.log(err)
    },3000);
    return Promise.reject(err);
  });

export default util;
